package org.jeecg.modules.flower.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.exception.FlowerSubTagInfoException;
import org.jeecg.modules.flower.mapper.FlowerTagInfoMapper;
import org.jeecg.modules.flower.service.*;
import org.jeecg.modules.flower.vo.CountNumData;
import org.jeecg.modules.flower.vo.ScreenData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Description: 标签信息
 * @Author: jeecg-boot
 * @Date: 2021-08-26
 * @Version: V1.0
 */
@Service
@Slf4j
public class FlowerTagInfoServiceImpl extends ServiceImpl<FlowerTagInfoMapper, FlowerTagInfo> implements IFlowerTagInfoService {
    @Autowired
    private IFlowerOutlogService flowerOutlogService;
    @Autowired
    private ITFlowerTagIn2Service flowerTagIn2Service;
    @Autowired
    private IFlowerOutorderPrtService flowerOutorderPrtService;
    @Autowired
    private IFlowerTagpreService flowerTagpreService;

    @Resource
    private IFlowerLoseInfoService flowerLoseInfoService;
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public IPage<FlowerTagInfo> queryListAndBase(IPage<FlowerTagInfo> page, Wrapper<FlowerTagInfo> queryWrapper) {
        return baseMapper.queryListAndBase(page, queryWrapper);
    }


    @Override
    public IPage<ScreenData> selectTablePage(IPage<ScreenData> page, Wrapper<ScreenData> queryWrapper) {
        return baseMapper.selectTablePage(page, queryWrapper);
    }

    @Override
    public List<ScreenData> poleLengthCom() {
        return baseMapper.poleLengthCom();
    }

    @Override
    public List<ScreenData> monthWorkCom() {
        return baseMapper.monthWorkCom();
    }

    @Override
    public CountNumData currentSortFlower() {
        return baseMapper.currentSortFlower();
    }

    @Override
    public LinkedHashMap<String, Object> queryPoleLevelYear() {
        return baseMapper.queryPoleLevelYear();
    }

    @Override
    public LinkedHashMap<String, Object> queryPoleLevelMonth() {
        return baseMapper.queryPoleLevelMonth();
    }

    @Override
    public List<LinkedHashMap<String, Object>> queryVariety() {
        return baseMapper.queryVariety();
    }


    private final static String LOKETAG = "FLOWERTAG2001";

    @Override
    public String flowerCountMessage() {
        // 获取上周一到周五的日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -7);
        int day_of_week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (day_of_week == 0) {
            day_of_week = 7;
        }
        calendar.add(Calendar.DATE, -day_of_week + 1);
        String startDate = format.format(calendar.getTime());
        calendar.add(Calendar.DAY_OF_WEEK, 4);
        String endDate = format.format(calendar.getTime());
        String sql = "SELECT\n" +
                "ifnull(sum( 1 ),0) totalVariety,\n" +
                "ifnull(sum( wrap ),0) totalWrap,\n" +
                "ifnull(sum( flowerCount ),0) totalFlowerCount\n" +
                "FROM\n" +
                "\t(\n" +
                "\tSELECT\n" +
                "\tcount( 1 ) wrap,\n" +
                "\tb.item_text planting_variety,\n" +
                "\tc.item_value,\n" +
                "\tsum(\n" +
                "CASE\n" +
                "\t\n" +
                "\tWHEN c.item_value = '1' \n" +
                "\tOR c.item_value = '3' THEN\n" +
                "\t10 \n" +
                "\tWHEN c.item_value = '2' THEN\n" +
                "\t20 ELSE 0 \n" +
                "END \n" +
                "\t) flowerCount \n" +
                "FROM\n" +
                "\tt_flower_tag_info a\n" +
                "\tLEFT JOIN ( SELECT item_value, item_text FROM sys_dict_item WHERE dict_id = ( SELECT id FROM sys_dict WHERE dict_code = 'planting_variety' ) ) b ON a.variety = b.item_value\n" +
                "\tLEFT JOIN (\n" +
                "SELECT\n" +
                "\titem_value,\n" +
                "\titem_text \n" +
                "FROM\n" +
                "\tsys_dict_item \n" +
                "WHERE\n" +
                "\tdict_id = ( SELECT id FROM sys_dict WHERE dict_code = 'planting_packing_specifications' ) \n" +
                "\tAND item_value IN ( '1', '2', '3' ) \n" +
                "\t) c ON a.packing_specifications = c.item_value \n" +
                "WHERE\n" +
                "\tc.item_text IS NOT NULL \n" +
                "\tand a.sort_time >= (SELECT STR_TO_DATE('" + startDate + "','%Y-%m-%d')) and a.sort_time <= (select STR_TO_DATE('" + endDate + "','%Y-%m-%d'))\n" +
                "GROUP BY\n" +
                "\tb.item_text,\n" +
                "\tc.item_value \n" +
                "\t) d ";

        log.info(sql);
        // 查询统计数
        Map<String, Object> map = jdbcTemplate.queryForMap(sql);
        StringBuilder ret = new StringBuilder();
        if (map.size() == 0) {
            ret.append("上周无产品信息录入");
        } else {

            BigDecimal totalVariety = (BigDecimal) map.get("totalVariety");
            BigDecimal totalWrap = (BigDecimal) map.get("totalWrap");
            BigDecimal totalFlowerCount = (BigDecimal) map.get("totalFlowerCount");
            ret.append("共采收").append(totalVariety).append("个产品，").append(totalWrap).append("，").append(totalFlowerCount).append("");
        }
        return ret.toString();
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Integer flowerLose(FlowerLose flowerLose) throws Exception {
        int dealNum = 0;
//        synchronized (LOKETAG) {
            QueryWrapper<FlowerTagInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("variety_code", flowerLose.getVarietyCode());
            queryWrapper.eq("packing_specifications", flowerLose.getPackingSpecifications());
        queryWrapper.eq("classes",flowerLose.getClasses());
            queryWrapper.eq("flower_pole_length", flowerLose.getFlowerPoleLength());
            queryWrapper.eq("storehouse", flowerLose.getStorehouse());
//        queryWrapper.eq("classify",flowerLose.getClassify());
            queryWrapper.eq("state", "1");
            queryWrapper.orderByAsc("sort_time");
            Integer loseNum = flowerLose.getLoseNum();

            int pageSize = 1000;
            int endPage = loseNum % pageSize > 0 ? (loseNum / pageSize + 1) : loseNum / pageSize;
            for (int pageNo = 1; pageNo <= endPage; pageNo++) {
                if (pageNo * pageSize > loseNum) {
                    pageSize = loseNum;
                }
                List<String> tagInfoIds = new ArrayList<>();
                Page<FlowerTagInfo> page = new Page<>(pageNo, pageSize);
                IPage<FlowerTagInfo> pageList = this.page(page, queryWrapper);
                List<FlowerLoseInfo> flowerLoseInfos = new ArrayList<>();
                List<FlowerTagInfo> flowerTagInfos = pageList.getRecords();
                for (FlowerTagInfo flowerTagInfo : flowerTagInfos) {
                    FlowerLoseInfo flowerLoseInfo = new FlowerLoseInfo();
                    flowerLoseInfo.setFlowerLoseId(flowerLose.getId());
                    flowerLoseInfo.setTagInId(flowerTagInfo.getId());
                    flowerLoseInfos.add(flowerLoseInfo);
                    tagInfoIds.add(flowerTagInfo.getId());
                }
                flowerLoseInfoService.saveBatch(flowerLoseInfos);

                this.updateStateToLose(tagInfoIds);

                dealNum += flowerTagInfos.size();
            }
//        }
        return dealNum;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateStateToLose(List<String> tagInfoIds) throws Exception {
        UpdateWrapper<FlowerTagInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("state", "3");
        updateWrapper.in("id", tagInfoIds);
        this.update(updateWrapper);
    }

    @Override
    public IPage<FlowerTagInfo> getListByhose(IPage<FlowerTagInfo> page, Wrapper<FlowerTagInfo> wrapper) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        return baseMapper.getListByhose(page, wrapper, sysUser.getId());
    }

    //台账总数的查询接口
    @Override
    public Integer getTaginfoCount(Wrapper<FlowerTagInfo> wrapper) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        return baseMapper.getTaginfoCount(wrapper, sysUser.getId());
    }

    ;


    /**
     * 扣减库存-生成日志---直接出库
     *
     * @param outOrderInfoID
     * @param varietyCode
     * @param storehouse
     * @param packingSpecifications
     * @param flowerPoleLength
     * @param number
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer outTagInfo(String outOrderInfoID,String sourceBase,String sourceGreenhouse,  String variety, String varietyCode, String storehouse, String classes,String cost, String packingSpecifications, String flowerPoleLength, Integer number, Date stockOutTime) {
        Integer rest = 0;
//        synchronized (LOKETAG) {
            LambdaQueryWrapper<FlowerTagInfo> taginfoQuery = new LambdaQueryWrapper<>();
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
            taginfoQuery.eq(FlowerTagInfo::getSourceBase, sourceBase);
            taginfoQuery.eq(FlowerTagInfo::getSourceGreenhouse, sourceGreenhouse);
            taginfoQuery.eq(FlowerTagInfo::getVarietyCode, varietyCode);
            taginfoQuery.eq(FlowerTagInfo::getStorehouse, storehouse);
            taginfoQuery.eq(FlowerTagInfo::getClasses, classes);
            taginfoQuery.eq(FlowerTagInfo::getCost, cost);
            taginfoQuery.eq(FlowerTagInfo::getPackingSpecifications, packingSpecifications);
            taginfoQuery.eq(FlowerTagInfo::getFlowerPoleLength, flowerPoleLength);
            taginfoQuery.eq(FlowerTagInfo::getState, 1);//已入库的台账
            taginfoQuery.orderByAsc(FlowerTagInfo::getSortTime);

            Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(1, number);
            IPage<FlowerTagInfo> tageinfoPage = this.baseMapper.selectPage(page, taginfoQuery);
            List<FlowerTagInfo> taginfoRecords = tageinfoPage.getRecords();

            if (taginfoRecords.size() < number) {
                log.error(variety + "-" + varietyCode + "（" + storehouse + "-" + packingSpecifications + "-" + flowerPoleLength + "）" + "库存不足" + number + "（库存数量" + taginfoRecords.size() + "），请修改数量！");
                throw new FlowerSubTagInfoException(variety + "-" + varietyCode + "（" + storehouse + "-" + packingSpecifications + "-" + flowerPoleLength + "）" + "库存不足" + number + "（库存数量" + taginfoRecords.size() + "），请修改数量！");
            }

            List<String> tagInfoIds = new ArrayList<>();
            List<FlowerOutlog> flowerOutlogList = new ArrayList<>();
            for (FlowerTagInfo flowerTagInfo : taginfoRecords) {
                tagInfoIds.add(flowerTagInfo.getId());
                //	生成出库流水
                FlowerOutlog flowerOutlog = new FlowerOutlog();
                flowerOutlog.setTagId(flowerTagInfo.getId());//入库台账id
                flowerOutlog.setOutorderId(outOrderInfoID);//出库单子表id
                flowerOutlog.setState("0");
                flowerOutlogList.add(flowerOutlog);
                rest++;
            }
            saveLogs(flowerOutlogList);

            UpdateWrapper<FlowerTagInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("state", 2);
            updateWrapper.set("stock_out_time", stockOutTime);
            updateWrapper.set("stock_out_user", sysUser.getUsername());
            updateWrapper.in("id", tagInfoIds);
            this.update(updateWrapper);//修改入库台账
//        }
        return rest;
    }

    @Async
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void saveLogs(List<FlowerOutlog>  flowerOutlogList){
        flowerOutlogService.saveBatch(flowerOutlogList);
    }

    /**
     * 扣减库存-生成日志---PDA扫码出库
     *
     * @return java.lang.Integer
     * @descriptionauthor
     * @author gf
     * 2022-11-9 14:11
     * [orderID, map, stockOutTime]
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer outTagInfoForPDA(String orderID, Map<String, FlowerOutorderHZ> map, Date stockOutTime) {
        Integer rest = 0;
        synchronized (LOKETAG) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
            QueryWrapper<FlowerTagInfo> taginfoQuery = new QueryWrapper<>();
            taginfoQuery.inSql("in_id", " select id from   t_flower_tag_in tagin where  tagprint_id in " +
                    "(select print_id from t_flower_outorder_prt prt where prt.order_id='" + orderID + "')  ");
            List<FlowerTagInfo> taginfoLists = this.list(taginfoQuery);

            QueryWrapper<TFlowerTagIn2> inQueryWrapper = new QueryWrapper<>();
            inQueryWrapper.inSql("tagprint_id", "select print_id from t_flower_outorder_prt prt where prt.order_id='" + orderID + "'");
            List<TFlowerTagIn2> inlist = flowerTagIn2Service.list(inQueryWrapper);
            Map<String, String> mapIn = new HashMap<>();
            for (TFlowerTagIn2 flowerTagIn2 : inlist) {
                mapIn.put(flowerTagIn2.getId(), flowerTagIn2.getTagprintId());
            }

            List<String> tagInfoIds = new ArrayList<>();
            List<FlowerOutlog> flowerOutlogList = new ArrayList<>();
            for (FlowerTagInfo flowerTagInfo : taginfoLists) {
                if (!"1".equals(flowerTagInfo.getState())) {
                    throw new FlowerSubTagInfoException("确认出库失败！存在已出库的产品被扫码：" + flowerTagInfo.getStorehouse() + "-" + flowerTagInfo.getVariety()
                            + "-" + flowerTagInfo.getFlowerPoleLength());
                }
                tagInfoIds.add(flowerTagInfo.getId());


//、、先进先出的有标签的花，，，找一个把他代替了。
//、、先进先出的有标签的花，，，找一个把他代替了。
//、、先进先出的有标签的花，，，找一个把他代替了。
//、、先进先出的有标签的花，，，找一个把他代替了。
//、、先进先出的有标签的花，，，找一个把他代替了。
//、、先进先出的有标签的花，，，找一个把他代替了。
//、、先进先出的有标签的花，，，找一个把他代替了。
//、、先进先出的有标签的花，，，找一个把他代替了。


                FlowerOutorderHZ flowerOutorderHZ = map.get(flowerTagInfo.getStorehouse() + "_" + flowerTagInfo.getVarietyCode());
                String outOrderinfoID = flowerOutorderHZ.getOutOrderinfoID();
                if (StringUtils.isBlank(outOrderinfoID)) {
                    throw new FlowerSubTagInfoException("没有对应出库单，请仔细检查扫码产品和出库产品是否一致！" + flowerOutorderHZ.getVariety() + "-" + flowerOutorderHZ.getStorehouse());
                }

                //	生成出库流水
                FlowerOutlog flowerOutlog = new FlowerOutlog();
                flowerOutlog.setTagId(flowerTagInfo.getId());//入库台账id
                flowerOutlog.setOutorderId(outOrderinfoID);//出库单子表id
                flowerOutlog.setState("0");
                flowerOutlog.setPrintId(mapIn.get(flowerTagInfo.getInId()));
                flowerOutlog.setInId(flowerTagInfo.getInId());
                flowerOutlogList.add(flowerOutlog);
                rest++;
            }
            saveLogs(flowerOutlogList);

            UpdateWrapper<FlowerTagInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("state", 2);
            updateWrapper.set("stock_out_time", stockOutTime);
            updateWrapper.set("stock_out_user", sysUser.getUsername());
            updateWrapper.in("id", tagInfoIds);
            this.update(updateWrapper);//修改入库台账
        }
        return rest;
    }


    /**
     * 返还库存-删除日志---直接出库
     *
     * @param outOrderInfoID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer BackOutTagInfo(String outOrderInfoID) {
        Integer rest = 0;
        LambdaQueryWrapper<FlowerOutlog> outlogWrapper = new LambdaQueryWrapper<>();
        outlogWrapper.eq(FlowerOutlog::getOutorderId, outOrderInfoID);
        outlogWrapper.eq(FlowerOutlog::getState, 0);
        List<FlowerOutlog> flowerOutlogList = flowerOutlogService.list(outlogWrapper);
        List<String> tagInfoIds = new ArrayList<>();
        List<String> logidList = new ArrayList<>();
        List<String> printdList = new ArrayList<>();
        for (FlowerOutlog flowerOutlog : flowerOutlogList) {
            logidList.add(flowerOutlog.getId());
            //4、返回台账数据
            String tagId = flowerOutlog.getTagId();
            tagInfoIds.add(tagId);
            String printId = flowerOutlog.getPrintId();
            printdList.add(printId);
        }
        UpdateWrapper<FlowerTagInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("state", 1);
        updateWrapper.set("stock_out_time", null);
        updateWrapper.set("stock_out_user", "");
        updateWrapper.in("id", tagInfoIds);
        this.update(updateWrapper);//归还入库台账

        flowerOutlogService.removeByIds(logidList);//删流水

        //如果是扫码出库的-修改扫码标签的状态。。-2022年11月9日16:14:46
        UpdateWrapper<FlowerOutorderPrt> prtUpdateWrapper = new UpdateWrapper<>();
        prtUpdateWrapper.set("state", 0);
        prtUpdateWrapper.in("print_id", printdList);
        flowerOutorderPrtService.update(prtUpdateWrapper);
        return rest;
    }


    /**
     * 扣减库存- ==预出库
     *
     * @param outOrderInfoID
     * @param varietyCode
     * @param storehouse
     * @param packingSpecifications
     * @param flowerPoleLength
     * @param number
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer outPreTagInfo(String outOrderInfoID,String sourceBase,String sourceGreenhouse,  String channel, String accountno, String variety, String varietyCode, String storehouse,String classes,String cost, String packingSpecifications, String flowerPoleLength, Integer number, Date stockOutTime) {
        Integer rest = 0;
//        synchronized (LOKETAG) {
            LambdaQueryWrapper<FlowerTagInfo> taginfoQuery = new LambdaQueryWrapper<>();
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
            taginfoQuery.eq(FlowerTagInfo::getSourceBase, sourceBase);
            taginfoQuery.eq(FlowerTagInfo::getSourceGreenhouse, sourceGreenhouse);
            taginfoQuery.eq(FlowerTagInfo::getVarietyCode, varietyCode);
            taginfoQuery.eq(FlowerTagInfo::getStorehouse, storehouse);
            taginfoQuery.eq(FlowerTagInfo::getClasses, classes);
            taginfoQuery.eq(FlowerTagInfo::getPackingSpecifications, packingSpecifications);
            taginfoQuery.eq(FlowerTagInfo::getFlowerPoleLength, flowerPoleLength);
            taginfoQuery.eq(FlowerTagInfo::getCost, cost);

            taginfoQuery.eq(FlowerTagInfo::getState, 1);//已入库的台账
            taginfoQuery.orderByAsc(FlowerTagInfo::getSortTime);

            Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(1, number);
            IPage<FlowerTagInfo> tageinfoPage = this.baseMapper.selectPage(page, taginfoQuery);
            List<FlowerTagInfo> taginfoRecords = tageinfoPage.getRecords();

            if (taginfoRecords.size() != number) {
                log.error(variety + varietyCode + "（" + packingSpecifications + "-" + flowerPoleLength + "）" + "库存不足" + number + "（库存数量" + taginfoRecords.size() + "），请修改数量！");
                throw new FlowerSubTagInfoException(variety + varietyCode + "（" + packingSpecifications + "-" + flowerPoleLength + "）" + "库存不足" + number + "（库存数量" + taginfoRecords.size() + "），请修改数量！");
            }

            List<String> tagInfoIds = new ArrayList<>();
            List<FlowerTagpre> tagpresLists = new ArrayList<>();
            for (FlowerTagInfo flowerTagInfo : taginfoRecords) {
                tagInfoIds.add(flowerTagInfo.getId());

                //生成预出库台账
                FlowerTagpre flowerTagpre = new FlowerTagpre();
                flowerTagpre.setInId(flowerTagInfo.getId());//入库台账id
                flowerTagpre.setOutorderId(outOrderInfoID);//出库单子表id
                flowerTagpre.setStorehouse(flowerTagInfo.getStorehouse());
                flowerTagpre.setCost(flowerTagInfo.getCost());
                flowerTagpre.setSourceBase(flowerTagInfo.getSourceBase());
                flowerTagpre.setSourceGreenhouse(flowerTagInfo.getSourceGreenhouse());
                flowerTagpre.setVariety(flowerTagInfo.getVariety());
                flowerTagpre.setVarietyCode(flowerTagInfo.getVarietyCode());
                flowerTagpre.setPackingSpecifications(flowerTagInfo.getPackingSpecifications());
                flowerTagpre.setClasses(flowerTagInfo.getClasses());
                flowerTagpre.setFlowerPoleLength(flowerTagInfo.getFlowerPoleLength());
                flowerTagpre.setChannel(channel);//渠道
                flowerTagpre.setAccountno(accountno);//账号
                flowerTagpre.setStockOutTime(stockOutTime);//出库时间
                flowerTagpre.setStockOutUser(sysUser.getRealname());//出库人
                flowerTagpre.setStockInTime(flowerTagInfo.getStockInTime());
                flowerTagpre.setStockInUser(flowerTagInfo.getStockInUser());
                flowerTagpre.setState(1);
                tagpresLists.add(flowerTagpre);
                rest++;
            }
            UpdateWrapper<FlowerTagInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("state", 2);
            updateWrapper.set("stock_out_time", stockOutTime);
            updateWrapper.set("stock_out_user", sysUser.getUsername());
            updateWrapper.in("id", tagInfoIds);
            this.update(updateWrapper);//修改入库台账
//        flowerTagpreService.saveBatch(tagpresLists);//保存预出库台账
            saveTagPre(tagpresLists);//保存预出库台账
//        }
        return rest;
    }

    /**
     * 扣减库存- ==预出库---PDA扫码预出库
     *
     * @return java.lang.Integer
     * @descriptionauthor
     * @author gf
     * 2022-11-10 9:43
     * [orderID, channel, accountno, map, stockOutTime]
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer outPreTagInfoPDA(String orderID, String channel, String accountno, Map<String, FlowerOutorderHZ> map, Date stockOutTime) {
        Integer rest = 0;
        synchronized (LOKETAG) {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

            QueryWrapper<FlowerTagInfo> taginfoQuery = new QueryWrapper<>();
            taginfoQuery.inSql("in_id", " select id from   t_flower_tag_in tagin where  tagprint_id in " +
                    "(select print_id from t_flower_outorder_prt prt where prt.order_id='" + orderID + "')  ");
            List<FlowerTagInfo> taginfoLists = this.list(taginfoQuery);

            List<String> tagInfoIds = new ArrayList<>();
            List<FlowerTagpre> tagpresLists = new ArrayList<>();
            for (FlowerTagInfo flowerTagInfo : taginfoLists) {
                tagInfoIds.add(flowerTagInfo.getId());

                FlowerOutorderHZ flowerOutorderHZ = map.get(flowerTagInfo.getStorehouse() + "_" + flowerTagInfo.getVarietyCode());
                //生成预出库台账
                FlowerTagpre flowerTagpre = new FlowerTagpre();
                flowerTagpre.setInId(flowerTagInfo.getId());//入库台账id
                flowerTagpre.setOutorderId(flowerOutorderHZ.getOutOrderinfoID());//出库单子表id
                flowerTagpre.setStorehouse(flowerTagInfo.getStorehouse());
                flowerTagpre.setCost(flowerTagInfo.getCost());
                flowerTagpre.setSourceBase(flowerTagInfo.getSourceBase());
                flowerTagpre.setSourceGreenhouse(flowerTagInfo.getSourceGreenhouse());
                flowerTagpre.setVariety(flowerTagInfo.getVariety());
                flowerTagpre.setVarietyCode(flowerTagInfo.getVarietyCode());
                flowerTagpre.setPackingSpecifications(flowerTagInfo.getPackingSpecifications());
                flowerTagpre.setClasses(flowerTagInfo.getClasses());
                flowerTagpre.setFlowerPoleLength(flowerTagInfo.getFlowerPoleLength());
                flowerTagpre.setChannel(channel);//渠道
                flowerTagpre.setAccountno(accountno);//账号
                flowerTagpre.setStockOutTime(stockOutTime);//出库时间
                flowerTagpre.setStockOutUser(sysUser.getRealname());//出库人
                flowerTagpre.setStockInTime(flowerTagInfo.getStockInTime());
                flowerTagpre.setStockInUser(flowerTagInfo.getStockInUser());
                flowerTagpre.setState(1);
                tagpresLists.add(flowerTagpre);
                rest++;
            }
            UpdateWrapper<FlowerTagInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("state", 2);
            updateWrapper.set("stock_out_time", stockOutTime);
            updateWrapper.set("stock_out_user", sysUser.getUsername());
            updateWrapper.in("id", tagInfoIds);
            this.update(updateWrapper);//修改入库台账
//            flowerTagpreService.saveBatch(tagpresLists);//保存预出库台账
            saveTagPre(tagpresLists);//保存预出库台账
        }
        return rest;
    }
    @Async
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public void saveTagPre(List<FlowerTagpre>  tagpresLists){
        flowerTagpreService.saveBatch(tagpresLists);//保存预出库台账
    }
    /**
     * 撤销---返还库存- ==预出库
     *
     * @param outOrderInfoID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer BackPreOutTagInfo(String outOrderInfoID) {
        Integer rest = 0;

        LambdaQueryWrapper<FlowerTagpre> tagpreLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tagpreLambdaQueryWrapper.eq(FlowerTagpre::getOutorderId, outOrderInfoID);
//        tagpreLambdaQueryWrapper.eq(FlowerTagpre::getState,1);  //gf2022年9月19日22:12:18优化，不在查找为1的数据，直接在循环里判断。
        List<FlowerTagpre> list = flowerTagpreService.list(tagpreLambdaQueryWrapper);
        List<String> tagInfoIds = new ArrayList<>();
        List<String> tagpreIds = new ArrayList<>();
        String inIds = "''";
        if(list.size()<=0){
            throw new RuntimeException("数据存在错误，请联系管理员。预出库子表id：" + outOrderInfoID);
        }
        for (FlowerTagpre flowerTagpre : list) {
            //gf2022年9月19日22:12:18优化，不在查找为1的数据，直接在循环里判断。
            Integer state = flowerTagpre.getState();
            if (state != 1 && !"1".equals(state)) {
                throw new RuntimeException("存在已经销售确认的数据，请先删除确认数据，才能进行删除预出库。" + flowerTagpre.getOutorderId());
            }
            //---end----gf2022年9月19日22:12:18优化，不在查找为1的数据，直接在循环里判断。
            //1、返回台账数据
            String tagId = flowerTagpre.getInId();
            inIds += ",'" + tagId + "'";
            tagInfoIds.add(tagId);
            tagpreIds.add(flowerTagpre.getId());
        }
        UpdateWrapper<FlowerTagInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("state", 1);
        updateWrapper.set("stock_out_time", null);
        updateWrapper.set("stock_out_user", "");
        updateWrapper.in("id", tagInfoIds);
        boolean update = this.update(updateWrapper);//归还入库台账

        log.info("查找预出库申请删除后预出库台账未删除情况==========归还预出库台账：归还入库台账" + tagInfoIds.toString() + "===" + update);
        //删除预出库台账
        boolean remove = flowerTagpreService.removeByIds(tagpreIds);
        log.info(outOrderInfoID + "查找预出库申请删除后预出库台账未删除情况==========归还预出库台账：删除getOutorderId为" + tagpreIds + " 的预出库台账数据局：" + remove);

        //如果扫码出库，则修改扫码标签表的状态，gf2022年11月10日09:12:53

        UpdateWrapper<FlowerOutorderPrt> prtUpdateWrapper = new UpdateWrapper<>();
        prtUpdateWrapper.set("state", 0);
        prtUpdateWrapper.inSql("print_id", "select tagin.tagprint_id from t_flower_tag_in tagin " +
                "where tagin.id in (select  in_id from t_flower_tag_info   where id in (" + inIds + ")  )");
        boolean update1 = flowerOutorderPrtService.update(prtUpdateWrapper);
        return rest;
    }
}
